package gui

import (
	"fmt"
	"strings"

	"mcp-clarification-service/internal/tools"
)

func formatAnswerSummaryLines(q tools.Question, answer tools.Answer) []string {
	lines := []string{}

	switch q.Type {
	case "single":
		if answer.SelectedIndex != nil {
			idx := *answer.SelectedIndex
			if idx >= 0 && idx < len(q.Options) {
				lines = append(lines, fmt.Sprintf("选择：%s", q.Options[idx]))
			}
		}
		if strings.TrimSpace(answer.AdditionalInput) != "" {
			lines = append(lines, fmt.Sprintf("其他：%s", strings.TrimSpace(answer.AdditionalInput)))
		}
		if len(lines) == 0 {
			lines = append(lines, "未选择")
		}

	case "multiple":
		if len(answer.SelectedIndices) > 0 {
			for _, idx := range answer.SelectedIndices {
				if idx >= 0 && idx < len(q.Options) {
					lines = append(lines, fmt.Sprintf("选择：%s", q.Options[idx]))
				}
			}
		}
		if len(lines) == 0 {
			// 回退到附加文本或未选择
			combined := []string{}
			for _, idx := range answer.SelectedIndices {
				if idx >= 0 && idx < len(q.Options) {
					combined = append(combined, q.Options[idx])
				}
			}
			if len(combined) > 0 {
				lines = append(lines, fmt.Sprintf("选择：%s", strings.Join(combined, "，")))
			}
		}
		if strings.TrimSpace(answer.AdditionalInput) != "" {
			lines = append(lines, fmt.Sprintf("其他：%s", strings.TrimSpace(answer.AdditionalInput)))
		}
		if len(lines) == 0 {
			lines = append(lines, "未选择")
		}

	case "free_text":
		if strings.TrimSpace(answer.Text) != "" {
			lines = append(lines, fmt.Sprintf("回答：%s", answer.Text))
		} else {
			lines = append(lines, "未填写")
		}

	default:
		lines = append(lines, "未填写")
	}

	return lines
}

func formatAnswerSummaryText(q tools.Question, answer tools.Answer) string {
	return strings.Join(formatAnswerSummaryLines(q, answer), "\n")
}
